import datetime
import time

YYYY = "%Y"
YYYYMMDD = "%Y-%m-%d"
YYYYMMDD2 = "%Y%m%d"
YYYYMMDD3 = "%Y/%m/%d"
HHMMSS = "%H:%M:%S"
YYYYMMDDHHMMSS = "%Y-%m-%d %H:%M:%S"
MMDDHHMM = "%m月%d日 %H:%M"


# 获取当前时间戳  10位
def current_time():
    return int(time.time())


# 时间戳，13位
def stamp_ms(c_time=None):
    if c_time is None:
        c_time = time.time()
    curr_t = int(c_time * 1000)
    return curr_t


# 时间戳比较
def compar_stamp(time1, time2):
    if time1 > time2:
        return True
    else:
        return False


# 格式化成“fmt_str”指定格式
def fmt_d(c_time=None, fmt_str=None):
    if c_time is None:
        c_time = time.time()
    if fmt_str is None:
        fmt_str = YYYYMMDDHHMMSS
    return time.strftime(fmt_str, time.localtime(c_time))


# 获取指定 字符日期 的前后时间
# period=0   天
# period=1   分钟
def get_assing_day(str_time, strtimefomat, n, period=0, resulformat=YYYYMMDD):
    result_date = str2datetime(str_time, strtimefomat)
    if period == 0:
        return (result_date + datetime.timedelta(days=n)).strftime(resulformat)

    if period == 1:
        return (result_date + datetime.timedelta(minutes=n)).strftime(YYYYMMDDHHMMSS)


# 获取指定 时间戳日期 的前后时间
# period=0   天
# period=1   分钟
def get_assign_dat(stamp_time, strtimefomat, n, period=0):
    result_date = datetime.datetime.fromtimestamp(stamp_time)
    if period == 0:
        return (result_date + datetime.timedelta(days=n)).strftime(strtimefomat)
    if period == 1:
        return (result_date + datetime.timedelta(minutes=n)).strftime(strtimefomat)


# 将字符串格式的时间转换成时间戳（单位毫秒）
def stamp_time(time_str, fmt_str=None):
    if time_str is None or len(time_str) == 0:
        return None

    if fmt_str is None:
        fmt_str = YYYYMMDDHHMMSS

    if fmt_str is MMDDHHMM:
        time_str = str(datetime.datetime.now().year) + "年" + time_str
        fmt_str = "%Y年" + fmt_str

    try:
        timeArray = time.strptime(time_str, fmt_str)
        timeStamp = int(time.mktime(timeArray))
        return timeStamp
    except Exception as e:
        print(e)
    return None


# 生成当前时间的时间戳，只有一个参数即时间戳的位数，默认为10位，输入位数即生成相应位数的时间戳，比如可以生成常用的13位时间戳
def now_to_timestamp(digits=10):
    time_stamp = time.time()
    digits = 10 ** (digits - 10)
    time_stamp = int(round(time_stamp * digits))
    return time_stamp


# 获取今天零时时间戳
def today_zero_stamp():
    return stamp_time(str(datetime.datetime.now().year) + "-" + str(datetime.datetime.now().month) + "-" + str(
        datetime.datetime.now().day), YYYYMMDD)


# 字符串时间转为datetime格式
def str2datetime(strtime, format):
    return datetime.datetime.strptime(strtime, format)


# 把datetime转成字符串
def datetime2Str(dt, format=None):
    if format is None:
        format = YYYYMMDDHHMMSS
    return dt.strftime(format)


# 时间戳转为字符串时间
def timestamp2str(timestamp, format):
    return time.strftime(format, time.localtime(timestamp))


# 两个String时间之差
def gap_time_str(time1, time2, format):
    return stamp_time(time1, format) - stamp_time(time2, format)
